function [x_mean,y_mean] = bin_data(x,y,num_bins)
%UNTITLED2 Summary of this function goes here
%   Detailed explanation goes here
% x quantiles

%x=fracdis_long;
%y=AA_iprop_long;
%num_bins=20;

% determine input matrix sizes
[nx,mx] = size(x);
[ny,my] = size(y);

qvals = 0:(1/num_bins):(1-1/num_bins);
x_quant = quantile(x,[qvals 1]);

% remove identical bins
x_quant = sort(unique(x_quant));

% due to interpolation, some bins can still be empty
x_quant2 = x_quant;
x_quant = x_quant(1);
count_bin = length(find(x>x_quant2(1)));
for i=2:length(x_quant2)
    count_bin2 = length(find(x>x_quant2(i)));
    if count_bin2 ~= count_bin
        x_quant = [x_quant x_quant2(i)];
    end
    count_bin = count_bin2;
end

% preallocate outputs
x_mean = zeros(length(x_quant)-1,1);
y_mean = zeros(length(x_quant)-1,1);
y_low  = zeros(length(x_quant)-1,1);
y_high = zeros(length(x_quant)-1,1);

% desired y range

    for i = 1:length(x_quant)-1
        idx = x >= x_quant(i) & (x < x_quant(i+1));

        m = mean(y(idx,:));
        s = std(y(idx,:));
        y_mean(i,:)  = m;
        y_low(i,:)  = m-s;
        y_high(i,:) = m+s;
        x_mean(i)    = mean(x(idx));

    end
end

